#!/usr/bin/python
# -*- coding: UTF-8 -*-
from flask import send_from_directory, abort, Flask, render_template, jsonify, request
import logging
from logging.handlers import RotatingFileHandler
import time
import os
from concurrent.futures import ThreadPoolExecutor
import shutil

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'static/upload'
app.config['PROCESSED_FOLDER'] = 'static/processed'
basedir = os.path.abspath(os.path.dirname(__file__))
ALLOWED_EXTENSIONS = {'txt', 'png', 'jpg', 'jpeg', 'xls', 'JPG', 'JPEG', 'PNG', 'xlsx', 'gif', 'GIF'}
app.config['SECRET_KEY'] = 'secret!'
executor = ThreadPoolExecutor(4)


# 用于判断文件后缀
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


# 用于检测图片是否处理完了
@app.route("/api/done/<filename>", methods=['GET'])
def done(filename):
    new_filename = 'processed_' + filename
    app.logger.info(os.path.join(app.config['PROCESSED_FOLDER'], new_filename))
    if os.path.isfile(os.path.join(app.config['PROCESSED_FOLDER'], new_filename)):
        return jsonify({"code": 0, "imgurl": "/api/download/" + filename})
    return jsonify({"code": 1})


# 用于下载图片
@app.route("/api/download/<filename>", methods=['GET'])
def download(filename):
    filename = 'processed_' + filename
    app.logger.info(os.path.join(app.config['PROCESSED_FOLDER'], filename))
    if os.path.isfile(os.path.join(app.config['PROCESSED_FOLDER'], filename)):
        return send_from_directory(app.config['PROCESSED_FOLDER'], filename, as_attachment=True)
    abort(404)


# 获取首页
@app.route("/", methods=['GET'])
def index():
    return render_template('index.html')


# 上传文件
@app.route('/api/upload', methods=['POST'], strict_slashes=False)
def api_upload():
    file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
    f = request.files['myfile']  # 从表单的file字段获取文件，myfile为该表单的name值
    if f and allowed_file(f.filename):  # 判断是否是允许上传的文件类型
        ext = os.path.splitext(f.filename)[-1]  # 获取文件后缀
        unix_time = int(time.time())
        new_filename = str(unix_time) + ext  # 修改了上传的文件名
        f.save(os.path.join(file_dir, new_filename))  # 保存文件到upload目录
        executor.submit(process_img, new_filename)
        return jsonify({"code": 0, "errmsg": "上传成功", "fileName": "/api/done/" + new_filename})
    else:
        return jsonify({"code": 1001, "errmsg": "上传失败"})


# 图片处理函数，可以在这里调用图片处理API，图片处理完毕后一定要保存到static/processed路径下
def process_img(img_name):
    # 这里延时10s中，当做图片处理
    time.sleep(10)
    src_file = os.path.join(basedir, app.config['UPLOAD_FOLDER'], img_name)
    if not os.path.exists(src_file):
        print("file not exist")
        return
    dest_file = os.path.join(basedir, app.config['PROCESSED_FOLDER'], 'processed_' + img_name)
    app.logger.info(src_file)
    app.logger.info(dest_file)
    shutil.copy(src_file, dest_file)


if __name__ == '__main__':
    app.logger.setLevel(logging.INFO)
    info_log = os.path.join(app.root_path, 'log', 'app-info.log')
    info_file_handler = RotatingFileHandler(
        info_log, maxBytes=1048576, backupCount=20)
    info_file_handler.setLevel(logging.INFO)
    info_file_handler.setFormatter(
        logging.Formatter('%(asctime)s %(levelname)s: %(message)s '
                          '[in %(pathname)s:%(lineno)d]')
    )
    app.logger.addHandler(info_file_handler)
    app.run(debug=True)
